package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.ParameterException;
import com.demo.dao.CommentDao;
import com.demo.dao.LikeDao;
import com.demo.dao.PostDao;
import com.demo.domain.Comment;
import com.demo.domain.Like;
import com.demo.domain.Post;
import com.demo.domain.Reply;
import com.demo.domain.ro.SaveCmtRequest;
import com.demo.domain.vo.CommentView;
import com.demo.domain.vo.ReplyView;
import com.demo.service.CommentService;
import com.demo.service.MessageService;
import com.demo.service.ReplyService;
import com.demo.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentDao, Comment> implements CommentService {
    @Autowired
    private CommentDao commentDao;

    @Autowired
    private PostDao postDao;

    @Autowired
    private LikeDao likeDao;

    @Autowired
    private ReplyService replyService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private MessageService messageService;

    @Override
    public Result getPostCommentsWithReplies(Long postId, int currentPage,Long uid) {
        try {
            validateParameters(postId, currentPage);
            Comment comment = new Comment();
            comment.setPid(postId);
            int pageSize = 5;
            IPage<Comment> commentIPage = getCommentByCpId(currentPage, pageSize, comment);
            List<Comment> commentList = commentIPage.getRecords();
            List<CommentView> commentViewList = new ArrayList<>();
            for (Comment comment1 : commentList) {
                Long commentId = comment1.getId();
                Reply reply = new Reply();
                reply.setCid(commentId);
                List<ReplyView> replyList = replyService.getReplyWithoutPage(currentPage, reply,uid);
                CommentView commentView = new CommentView();
                commentView.setId(comment1.getId());
                System.out.println(uid);
                System.out.println(comment1.getId());
                Integer likeCount = likeDao.hasLikeComment(uid,comment1.getId()) ;
                commentView.setUnickname(comment1.getUnickname());
                commentView.setLikes(comment1.getLikes());
                commentView.setContent(comment1.getContent());
                commentView.setReleaseTime(comment1.getReleaseTime());
                commentView.setReplyList(replyList);
                if(likeCount != null){
                    commentView.setUserLikeFlag(true);
                }else{
                    commentView.setUserLikeFlag(false);
                }
                commentViewList.add(commentView);
            }

            return Result.success(HttpStatus.SUCCESS, "获取评论成功", commentViewList);
        } catch (ParameterException e) {
            return Result.error(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }

    @Override
    public IPage<Comment> getCommentByCpId(int currentPage, int pageSize, Comment comment) throws ParameterException {
        validatePageInfo(currentPage, pageSize, comment);

        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        if (comment.getPid() != null) {
            lqw.like(Comment::getPid, comment.getPid());
        }

        List<Comment> commentList = commentDao.selectList(lqw);
        if (commentList.isEmpty()) {
            return new Page<>(currentPage, pageSize);
        }

        commentList.sort(Comparator.comparingInt(Comment::getLikes).reversed());
        IPage<Comment> page = new Page<>(currentPage, pageSize);
        return commentDao.selectPage(page, lqw);
    }

    private void validateParameters(Long postId, int currentPage) throws ParameterException {
        if (postId == null || postId <= 0L) {
            throw new ParameterException("postId为空或非法");
        }
        if (currentPage <= 0) {
            throw new ParameterException("currentPage值非法");
        }
    }

    private void validatePageInfo(int currentPage, int pageSize, Comment comment) throws ParameterException {
        if (currentPage == 0 || pageSize == 0 || comment == null) {
            throw new ParameterException("分页信息为0或comment为空");
        }
    }

    public Result saveComment(SaveCmtRequest saveCmtRequest,Long uid) throws IOException, ParameterException {
        if (saveCmtRequest == null) {
            throw new ParameterException("commentRequest为空");
        }
        if (uid == null || uid < 0l) {
            throw new ParameterException("uid为空或值非法");
        }
        String content = saveCmtRequest.getContent();
        String unickname = saveCmtRequest.getUnickname();
        Long pid = saveCmtRequest.getPid();
        if (content.isEmpty() || unickname.isEmpty() || pid == null || pid <= 0L) {
            throw new ParameterException("commentRequest的必要属性含空值或非法值");
        }

        Comment comment = new Comment();
        comment.setContent(content);
        comment.setUnickname(unickname);
        comment.setPid(pid);
        comment.setUid(uid);
        Long toUid = postDao.selectUidBypid(pid);
        // 设置内容长度限制
        int maxContentLength = 1000;
        if (content.length() > maxContentLength) {
            throw new ParameterException("评论内容长度超过字数限制");
        }
        boolean flag = saveCommentFlag(comment);
        if(flag == true){
            webSocketServer.sendInfo("您有未读消息", toUid);
        }
        return flag ? Result.success(HttpStatus.SUCCESS, "添加成功", null) : Result.error("添加失败");
    }

    @Override
    public boolean saveCommentFlag(Comment comment) throws ParameterException {
        if (comment == null) {
            throw new ParameterException("参数comment为空");
        }
        if (comment.getContent() == null || comment.getContent().equals("")) {
            throw new ParameterException("评论内容为空");
        }
//        获取现在时间
        LocalDateTime localDateTime = LocalDateTime.now();
        comment.setReleaseTime(localDateTime);
        comment.setLikes(0);
        comment.setReadStatus(0);
        long pid = comment.getPid();
//        在发布评论时，增加统计的帖子的评论数
        postDao.incrementCommentsByPid(pid);
        return commentDao.insert(comment) > 0;
    }
}
